<?php

namespace App\Http\Controllers\Api;

use App\Common\ErrorCode;
use App\Models\Banner;
use App\Models\Book;
use App\Models\BookList;
use App\Models\BookRecommendPositionRelation;
use App\Models\Category;
use App\Models\User;
use Illuminate\Http\Request;
use DB;

class HomepageController extends BaseController
{
    public function index(Request $request)
    {
        $user_id = $request->input('user_id');

        if(empty($user_id))
        {
            return $this->error(ErrorCode::PARAMS_NOT_VALID_CODE,ErrorCode::PARAMS_NOT_VALID_MESSAGE);
        }
        $user = User::query()->find($user_id);

        $data = [
            'banners' => [],
            'good_book_lists' => [],
            'like_categories' => [],
            'douban_list' => [],
            'recommend_list' => [],
            'news_list' => [],
        ];
        //获取首页banners
        $banners = Banner::query()->select('id','url','image')->where('type',1)->orderBy('id','desc')->get();
        if(!empty($banners))
        {
            foreach ($banners as $banner)
            {
                $banner['image'] = config('app.qiniu_image_domain').DIRECTORY_SEPARATOR.$banner['image'];
                array_push($data['banners'],$banner);
            }
        }

        //精选书单
        $book_lists = BookList::query()->with(['user_collects'])->select('id','title','list_image','total_collect_num')->where('deleted',0)->where('is_recommend',1)->where('status',1)->limit(6)->orderBy('order','asc')->get();
        if(!empty($book_lists))
        {
            foreach ($book_lists as $v)
            {
                //共有多少本书
                $v['book_nums'] = DB::table('book_list_book_relations')->where('book_list_id',$v['id'])->count();
                $v['list_image'] = config('app.qiniu_image_domain').DIRECTORY_SEPARATOR.$v['list_image'];

                $user_collects = [];
                if(!empty($v->user_collects))
                {
                    foreach ($v->user_collects as $key=>$value)
                    {
                        if($key == 3)
                        {
                            break;
                        }
                        $user_collects[] = [
                            'user_id' => $value['id'],
                            'user_wechat_avatar' => $value['wechat_avatar']
                        ];
                    }
                }
                unset($v['user_collects']);
                //var_dump($user_collects);die;
                $v['user_collects'] = $user_collects;
                array_push($data['good_book_lists'],$v);
            }
        }

        //书单总数
        $data['book_list_total'] = BookList::query()->where('status',1)->where('deleted',0)->count();

        //非会员bannner
        $data['not_vip_banner'] = [];
        if(empty($user) || $user->is_vip != 1)
        {
            $banner = Banner::query()->where('type',4)->orderBy('id','desc')->first();
            if(!empty($banner))
            {
                $data['not_vip_banner'] = [
                    'type' => $banner->type,
                    'url' => $banner->url,
                    'image' => config('app.qiniu_image_domain').DIRECTORY_SEPARATOR.$banner->image,
                ];
            }
        }

        //猜您喜欢的分类
        $result = $user->getUserLikeCategory($user_id);

        $default_cate = [95,47,1,3];
        if(!$result[0]['category_id'])
        {
            //使用系统推荐的四个分类
            $category_ids = $default_cate;
        }
        else
        {
            foreach ($result as $v)
            {
                $category = Category::query()->where('id',$v['category_id'])->first();
                $category_ids[] = $category->parent_id;
            }
        }

        $cate_num = count($category_ids);
        if($cate_num < 4)
        {
            for ($i = 0;$i < (4-$cate_num);$i++)
            {
                $category_ids[] = $default_cate[$i];
            }
        }
        $categories = Category::query()->select('id','logo','title','book_total')->where('parent_id',0)->where('deleted',0)->whereIn('id',$category_ids)->limit(4)->get();
        if(!empty($categories))
        {
            foreach ($categories as $v)
            {
                $v['logo'] = config('app.qiniu_image_domain').DIRECTORY_SEPARATOR.$v['logo'];
                array_push($data['like_categories'],$v);
            }
        }

        //豆瓣高分
        $ids_arr = BookRecommendPositionRelation::query()->where('book_recommend_position_id',1)->pluck('book_id');
        $books = Book::query()->select('id','title','author','image','douban_score','category_id','intro','store')->with(['category'])->whereIn('id',$ids_arr)->limit(3)->where('on_sale',1)->where('deleted',0)->orderBy('douban_score','desc')->get();
        if(!empty($books))
        {
            foreach ($books as $item)
            {
                $item['intro'] = replace_intro($item['intro']);
                $item['image'] = config('app.qiniu_image_domain').DIRECTORY_SEPARATOR.$item['image'];
                array_push($data['douban_list'],$item);
            }
        }

        //小编力荐
        $ids_arr = BookRecommendPositionRelation::query()->where('book_recommend_position_id',2)->pluck('book_id');
        //print_r($ids_arr);
        $books = Book::query()->select('id','title','author','image','douban_score','category_id','total_read_num','intro','store')->with(['category'])->whereIn('id',$ids_arr)->where('deleted',0)->where('on_sale',1)->limit(6)->orderBy('total_read_num','desc')->get();
        if(!empty($books))
        {
            foreach ($books as $item)
            {
                $item['intro'] = replace_intro($item['intro']);
                $item['image'] = config('app.qiniu_image_domain').DIRECTORY_SEPARATOR.$item['image'];
                array_push($data['recommend_list'],$item);
            }
        }

        //最新出版
        $ids_arr = BookRecommendPositionRelation::query()->where('book_recommend_position_id',3)->pluck('book_id');
        //print_r($ids_arr);
        $books = Book::query()->select('id','title','author','image','douban_score','category_id','total_read_num','intro','store')->with(['category'])->where('on_sale',1)->where('deleted',0)->whereIn('id',$ids_arr)->limit(3)->orderBy('total_read_num','desc')->get();
        if(!empty($books))
        {
            foreach ($books as $item)
            {
                $item['intro'] = replace_intro($item['intro']);
                $item['image'] = config('app.qiniu_image_domain').DIRECTORY_SEPARATOR.$item['image'];
                array_push($data['news_list'],$item);
            }
        }

        return $this->res([
            'data' => $data
        ]);
    }

    public function recommend(Request $request)
    {
        $user_id = $request->input('user_id');

        if(empty($user_id))
        {
            return $this->error(ErrorCode::PARAMS_NOT_VALID_CODE,ErrorCode::PARAMS_NOT_VALID_MESSAGE);
        }

        $user = User::query()->find($user_id);
        $result = $user->getUserLikeCategory($user_id);

        $book_ids_arr = [];
        foreach ($result as $v)
        {
            $book_ids_arr = array_merge($book_ids_arr,$v['book_ids_arr']);
        }
        $book_ids_arr = array_values(array_unique($book_ids_arr));
        //var_dump($book_ids_arr);die;
        $ids = [];

        $book_ids_num = count($book_ids_arr);

        //var_dump($book_ids_num);die;
        if($book_ids_num > 3)
        {
            while (count($ids) < 3)
            {
                $num = random_int(1,$book_ids_num);
                if(!in_array($book_ids_arr[$num-1],$ids))
                {
                    $ids[] = $book_ids_arr[$num-1];
                }
            }
        }
        else
        {
            $ids = $book_ids_arr;
        }

        $data = [];
        $books = Book::query()->select('id','title','author','image','douban_score','category_id','total_read_num','intro','store', 'review_count')->with(['category'])->whereIn('id',$ids)->where('on_sale',1)->where('deleted',0)->get();
        if(!empty($books))
        {
            foreach ($books as $item)
            {
                $item['intro'] = replace_intro($item['intro']);
                $item['image'] = config('app.qiniu_image_domain').DIRECTORY_SEPARATOR.$item['image'];
                array_push($data,$item);
            }
        }

        return $this->res([
            'data' => $data
        ]);
    }
}
